package com.jindi.jacococli.biz.aop.cat;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CatTransactionAspect {
    @Around(value = "@annotation(catTransaction)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, CatTransaction catTransaction) throws Throwable {
        Transaction transaction = Cat.newTransaction(catTransaction.type(), catTransaction.name());
        Object result = null;
        try {
            if (StringUtils.isNotBlank(catTransaction.metric()) && !catTransaction.metric().equals("defaultMetric")) {
                Cat.logMetricForCount(catTransaction.metric(), 1);
            }

            Object[] args = proceedingJoinPoint.getArgs();
            result = proceedingJoinPoint.proceed(args);
            transaction.setStatus(Transaction.SUCCESS);
        } catch (Throwable e) {
            transaction.setStatus(e);
            throw e;
        } finally {
            transaction.complete();
        }
        return result;
    }
}
